[TOC]

Break & Continue

The keywords break and continue are used within a loop to abort looping entirely or to jump to the next iteration immediately. You need to be aware of the following facts when using the keywords:

  1. It is not allowed to use continue or break if the keyword is not enclosed by a loop.
  2. If continue or break is enclosed by several loops, it affects only the innermost loop that encloses it.

Continue

The keyword continue is used inside a loop to immediately start the next iteration, without executing the remaining statements in the current iteration.

Examples

Input
for i = 1:15
    if i <= 10
        continue
    end
    disp(i)
end
Output
 11.000

 12.000

 13.000

 14.000

 15.000
Input
for i = 1:5
    for j = 1:5
        if j >= 2
            continue
        end
        j
    end
    i
end
Output
j = 
 1.0000

i = 
 1.0000

j = 
 1.0000

i = 
 2.0000

j = 
 1.0000

i = 
 3.0000

j = 
 1.0000

i = 
 4.0000

j = 
 1.0000

i = 
 5.0000

Break

You use break inside a loop to immediately exit the loop without executing the remaining statements in the current iteration.

Examples

Input
for i = 1:100
    if i > 10
        break
    end
    disp(i)
end
Output
 1.0000

 2.0000

 3.0000

 4.0000

 5.0000

 6.0000

 7.0000

 8.0000

 9.0000

 10.000
Input
for i = 1:5
    for j = 1:5
        if j >= 2
            break
        end
        j
    end
    i
end
Output
j = 
 1.0000

i = 
 1.0000

j = 
 1.0000

i = 
 2.0000

j = 
 1.0000

i = 
 3.0000

j = 
 1.0000

i = 
 4.0000

j = 
 1.0000

i = 
 5.0000

Within switch Statement

The keywords break and continue are only allowed inside a loop. When they are found in a switch statement enclosed by loops, they only affect the innermost loop that encloses the switch statement. That means, a switch statement propagates the effect of break or continue to the innermost loop containing them. See the following two examples for illustration.

Examples

Input
value = 2;
for i = 1:10
    switch value
        case 1
            % Do something
        case 2
            if i >= 5
                continue
            end
    end
    i
end
Output
i = 
 1.0000

i = 
 2.0000

i = 
 3.0000

i = 
 4.0000
Input
value = 2;
for i = 1:10
    i
    switch value
        case 1
            % Do something
        case 2
            if i >= 5
                break
            end
    end
end
Output
i = 
 1.0000

i = 
 2.0000

i = 
 3.0000

i = 
 4.0000

i = 
 5.0000